package com.zlaidyrac.weride.main;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import com.google.gson.reflect.TypeToken;
import com.zlaidyrac.weride.persistence.User;
import com.zlaidyrac.weride.webclient.WebClient;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class HomeActivity extends Activity {

	String username;
	String password;
	public boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SharedPreferences userPrefs = getSharedPreferences("user_details", 0);
		if (userPrefs.getString("user_id", null) != null) {
			Common.loggedUser = new User();
			Common.loggedUser.setUserId(userPrefs.getString("user_id", null));
			Common.loggedUser.setUsername(userPrefs
					.getString("user_name", null));
			Common.loggedUser.setName(userPrefs.getString("name", null));
			Common.loggedUser.setContact(userPrefs.getString("contact", null));
			Common.loggedUser.setAddress(userPrefs.getString("address", null));
			Common.loggedUser.setGender(userPrefs.getString("gender", null));
			Common.loggedUser.setFbUrl(userPrefs.getString("fb_url", null));
			Intent tabs = new Intent(this, com.zlaidyrac.weride.ui.TabsActivity.class);
			startActivity(tabs);
			this.finish();

		}
		setContentView(R.layout.activity_login);

		Button login = (Button) findViewById(R.id.login);
		Button newUser = (Button) findViewById(R.id.button1);
		final EditText user = (EditText) findViewById(R.id.editText1);
		final EditText pass = (EditText) findViewById(R.id.editText2);

		newUser.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent nUser = new Intent(getApplicationContext(),
						com.zlaidyrac.weride.ui.NewUser.class);
				startActivity(nUser);
			}
		});

		login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				username = user.getText().toString();
				password = pass.getText().toString();

				if ((!(username.equals(""))) || (!(password.equals("")))) {
					HashMap<String, String> loginParams = new HashMap<String, String>();
					loginParams.put("username", username);
					loginParams.put("password", password);
					if ( isNetworkAvailable() ) {
						new LoginAsyncTask().execute(loginParams);
					}
					else {
						Toast.makeText(getApplicationContext(), "You need an active internet connection for WeRide" +
								" to work properly"	, Toast.LENGTH_LONG).show();
					}

				} else {

					AlertDialog.Builder validationBuilder = new AlertDialog.Builder(
							getApplicationContext());
					validationBuilder
							.setMessage(
									"Please enter both username and password")
							.setTitle("Error")
							.setPositiveButton("OK",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.dismiss();

										}
									});
					validationBuilder.create().show();
				}

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.home_screen, menu);
		return true;

	}

	private class LoginAsyncTask extends AsyncTask<HashMap<String, String>, Void, Boolean> {

		@Override
		protected Boolean doInBackground(HashMap<String, String>... params) {
			Type type = new TypeToken<User>(){}.getType();
			User user = (User)WebClient.postRequestForObject("login",params[0],WebClient.DECODE_OBJECT_TYPE_USER);
			
			if (user == null) {
				return false;
			} else {
				Common.loggedUser = user;
				/*for (String key : result.keySet()) {
					Common.loggedUser.setUserId(result.get("user_id"));
					Common.loggedUser.setUsername(result.get("user_name"));
					Common.loggedUser.setName(result.get("name"));
					Common.loggedUser.setContact(result.get("contact"));
					Common.loggedUser.setAddress(result.get("address"));
					Common.loggedUser.setGender(result.get("gender"));
					Common.loggedUser.setFbUrl(result.get("fb_url"));
					Log.i(key, result.get(key));
				}*/
				return true;

			}
		}

		protected void onPostExecute(Boolean loginSuccess) {
			super.onPostExecute(loginSuccess);
			if (loginSuccess) {
				Toast.makeText(getApplicationContext(), "Login Successful",
						Toast.LENGTH_SHORT).show();
				SharedPreferences userPreferences = getApplicationContext()
						.getSharedPreferences("user_details", 0);
				SharedPreferences.Editor editor = userPreferences.edit();
				editor.putString("user_id", Common.loggedUser.getUserId());
				editor.putString("user_name", Common.loggedUser.getUsername());
				editor.putString("name", Common.loggedUser.getName());
				editor.putString("email", Common.loggedUser.getEmail());
				editor.putString("contact", Common.loggedUser.getContact());
				editor.putString("address", Common.loggedUser.getAddress());
				editor.putString("gender", Common.loggedUser.getGender());
				editor.putString("fb_url", Common.loggedUser.getFbUrl());
				editor.commit();
				Intent tabs = new Intent(getApplicationContext(),
						com.zlaidyrac.weride.ui.TabsActivity.class);
				startActivity(tabs);
			} else {
				Toast.makeText(getApplicationContext(), "Login Failed",
						Toast.LENGTH_SHORT).show();
			}
		}

	}
}
